import { memo, useState } from 'react';
import { Form, Input, Button, Tabs, TabsProps } from 'antd';
import { UserOutlined, LockOutlined, MobileOutlined, KeyOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import './Login.css';
import { loginApi, registerApi } from '@/api/api';
import useApp from 'antd/es/app/useApp';
import useUserInfoStore from '@/store/useUserInfo';
import { useShallow } from 'zustand/shallow';

interface LoginParams {
  phone: string;
  password: string;
}

interface RegisterParams {
  username: string;
  phone: string;
  password: string;
}

// 登录和注册页面组件
const Login = () => {
  const navigate = useNavigate();
  const app = useApp();
  // 登录表单
  const [loginForm] = Form.useForm<LoginParams>();
  // 注册表单
  const [registerForm] = Form.useForm<RegisterParams>();
  // 当前选中的标签
  const [activeTab, setActiveTab] = useState('login');
  // 提交状态
  const [submitting, setSubmitting] = useState(false);
  // 仓库方法
  const { setUserInfo, setToken } = useUserInfoStore(
    useShallow((state) => ({
      setUserInfo: state.setUserInfo,
      setToken: state.setToken,
    }))
  );

  // 处理登录提交
  const handleLoginSubmit = async (values: LoginParams) => {
    setSubmitting(true);
    const res = await loginApi(values as any);
    if (res.code === 200) {
      app.message.success('登录成功');
      setUserInfo(res.data.userInfo);
      setToken(res.data.token);
      navigate('/');
    } else {
      app.message.error(res.message);
    }
    setSubmitting(false);
  };

  // 处理注册提交
  const handleRegisterSubmit = async (values: RegisterParams) => {
    setSubmitting(true);
    const res = await registerApi(values as any);
    if (res.code === 200) {
      app.message.success('注册成功');
      setActiveTab('login');
    } else {
      app.message.error(res.message);
    }
    setSubmitting(false);
  };

  // 标签页切换
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    // 切换页面时重置表单
    if (key === 'login') {
      loginForm.resetFields();
    } else {
      registerForm.resetFields();
    }
  };

  const tabList: TabsProps['items'] = [
    {
      key: 'login',
      label: '会员登录',
      children: (
        <div className="animate-fade-in-up">
          <Form
            form={loginForm}
            name="login"
            className="login-form"
            initialValues={{ remember: true }}
            onFinish={handleLoginSubmit}
          >
            {/* 手机号输入框 */}
            <Form.Item
              name="phone"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
              ]}
            >
              <Input
                prefix={<MobileOutlined />}
                placeholder="手机号"
                size="large"
                className="input-animate"
              />
            </Form.Item>

            {/* 密码输入框 */}
            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, max: 16, message: '密码长度在6-16位之间' },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="密码"
                size="large"
                className="input-animate"
              />
            </Form.Item>

            {/* 登录按钮 */}
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="login-button button-animate"
                loading={submitting}
                block
                size="large"
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      ),
    },
    {
      key: 'register',
      label: '立即注册',
      children: (
        <div className="animate-fade-in-up">
          <Form
            form={registerForm}
            name="register"
            className="register-form"
            onFinish={handleRegisterSubmit}
          >
            {/* 用户名输入框 */}
            <Form.Item
              name="username"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 3, max: 20, message: '用户名长度在3-20个字符之间' },
              ]}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="用户名"
                size="large"
                className="input-animate"
              />
            </Form.Item>

            {/* 手机号输入框 */}
            <Form.Item
              name="phone"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
              ]}
            >
              <Input
                prefix={<MobileOutlined />}
                placeholder="手机号"
                size="large"
                className="input-animate"
              />
            </Form.Item>

            {/* 密码输入框 */}
            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, max: 16, message: '密码长度在6-16位之间' },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="设置密码"
                size="large"
                className="input-animate"
              />
            </Form.Item>

            {/* 确认密码输入框 */}
            <Form.Item
              name="confirmPassword"
              dependencies={['password']}
              rules={[
                { required: true, message: '请确认密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password
                prefix={<KeyOutlined />}
                placeholder="确认密码"
                size="large"
                className="input-animate"
              />
            </Form.Item>

            {/* 注册按钮 */}
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="register-button button-animate"
                loading={submitting}
                block
                size="large"
              >
                注册
              </Button>
            </Form.Item>
          </Form>
        </div>
      ),
    },
  ];

  return (
    <div className="login-container">
      {/* 背景层 */}
      <div className="login-background"></div>

      {/* 内容层 */}
      <div className="login-content">
        <div className="login-card animate-fade-in">
          {/* 标题 */}
          <div className="login-header">
            <h1>传统文化学习平台</h1>
            <p>探索中华文化，传承千年智慧</p>
          </div>

          {/* 表单区域 */}
          <div className="login-form-wrapper">
            <Tabs
              activeKey={activeTab}
              onChange={handleTabChange}
              centered
              items={tabList}
            />
          </div>

          {/* 页脚版权信息 */}
          <div className="login-footer">
            <p>© {new Date().getFullYear()} 中华文化传承 版权所有</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default memo(Login);
